<style scoped lang="scss">
.el-upload {
  text-align: left;
}
.el-upload--text {
  background-color: #fff;
  /* border: 1px dashed #d9d9d9; */
  border-radius: 6px;
  box-sizing: border-box;
  width: 360px;
  height: 180px;
  text-align: left;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.el-upload--text .el-icon-upload {
  font-size: 67px;
  color: #97a8be;
  margin: 40px 0 16px;
  line-height: 50px;
}

.el-upload--text {
  color: #97a8be;
  font-size: 14px;
  text-align: center;
}

.el-upload--text em {
  font-style: normal;
}

.content-title {
  font-weight: 400;
  line-height: 50px;
  margin: 10px 0;
  font-size: 22px;
  color: #1f2f3d;
}

.pre-img {
  width: 80px;
  height: 80px;
  background: #f8f8f8;
  border: 1px solid #eee;
  border-radius: 5px;
}

.crop-demo {
  display: flex;
  align-items: flex-end;
}

.crop-demo-btn {
  position: relative;
  width: 100px;
  height: 40px;
  line-height: 40px;
  padding: 0 20px;
  margin-left: 30px;
  background-color: #409eff;
  color: #fff;
  font-size: 14px;
  border-radius: 4px;
  box-sizing: border-box;
}

.crop-input {
  position: absolute;
  width: 100px;
  height: 40px;
  left: 0;
  top: 0;
  opacity: 0;
  cursor: pointer;
}
</style>
<template>
  <div>
    <!-- cropper有待开发（待利用使用率更高的新插件重写） -->
    <div v-if="uploadType == 'cropper'">
      <div class="crop-demo">
        <img :src="cropImg" class="pre-img">
        <div class="crop-demo-btn">选择图片
          <input size="small" class="crop-input" type="file" name="image" accept="image/*" @change="setImage" />
        </div>
      </div>

      <el-dialog title="裁剪图片" :visible.sync="dialogVisible" width="30%">
        <!-- <vue-cropper ref='cropper' :src="imgSrc" :ready="cropImage" :zoom="cropImage" :cropmove="cropImage" style="width:100%;height:300px;"></vue-cropper> -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelCrop">取 消</el-button>
          <el-button type="primary" @click="uploadCropImg">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div v-else>
      <img :src="cropImg" class="pre-img">
      <el-upload :auto-upload="true" action="" :show-file-list="false" :http-request="uploadSectionFile">
        <!--此处使用自定义上传实现http-request-->
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传{{fileType.toString()}}文件，且不超过{{fileSize}}kb</div>
      </el-upload>
    </div>
    <div id="imgCropper"></div>
  </div>
</template>

<script>
import Cropper from "cropperjs";
export default {
  data: function() {
    return {
      fileList: [],
      imgSrc: "",
      cropImg: "",
      dialogVisible: false,
      fileObj: {}
    };
  },
  components: {},
  props: {
    fileType: {
      type: Array,
      require: true
    },
    fileSize: {
      type: Number,
      require: true
    },
    uploadType: String,
    defaultCroImg: String,
    croImgUrl: String,
    path: String
  },
  methods: {
    showPic(data) {
      //3.当用户上传图片后，触发input标签的onchange事件，执行showPic()方法
      if (data) {
        //4.判断input标签的file是否存在
        var reader = new FileReader(); //5.实例化一个FileReader()接口
        reader.readAsDataURL(data); //6.通过readAsDataURL()方法读取文件，将图片内嵌在网页之中
        reader.onload = evt => {
          //7.调用FileReader()的onload事件，当文件读取成功时，执行8
          this.cropImg = evt.target.result;
        };
      }
    },
    uploadSectionFile: function(param) {
      //自定义文件上传
      var fileObj = param.file;
      // 接收上传文件的后台地址
      var FileController = this.path + "rest/foru/apd/upload";
      // FormData 对象
      var form = new FormData();
      // 文件对象
      form.append("file", fileObj);
      // 其他参数
      form.append("filename", fileObj.name);
      form.append("filetype", fileObj.type.replace("image/", ""));
      this.$emit("imageUrl", "");
      this.$axios
        .post(this.path + "rest/foru/apd/upload", form, {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          var data = res.data;
          if (data.result == "true") {
            var resultData = data.resultData;
            this.showPic(fileObj);
            this.$emit("imageUrl", resultData.group + "/" + resultData.pathkey);
          } else {
            this.$error("图片读取失败，请重新选择");
          }
        })
        .catch(error => {
          this.$error("图片读取失败，请重新选择");
        });
    },
    /**@augments file 文件对象
     * 文件上传格式和大小限制
     */
    beforeUpload(file) {
      let isType = false;
      this.fileType.forEach(type => {
        if (type == file.type) {
          isType = true;
          return;
        }
      });
      let isLt2M = file.size / 1024 < this.fileSize;
      if (!isType) {
        this.$error("上传文件格式不正确!");
      }
      if (!isLt2M) {
        this.$error("上传头像图片大小不能超过" + this.fileSize + "KB!");
      }
      this.fileObj = file;
      return isType && isLt2M;
    },
    setImage(e) {
      let value = e.target.value;
      let files = e.target.files;
      if (!files || files.length == 0) {
        return;
      }
      let file = files[0];
      if (!file.type.includes("image/")) {
        return;
      }
      this.fileObj = file;
      let reader = new FileReader();
      reader.onload = event => {
        this.dialogVisible = true;
        this.imgSrc = event.target.result;
        // this.$refs.cropper && this.$refs.cropper.replace(event.target.result);
      };
      reader.readAsDataURL(file);
    },
    cropImage() {
      // this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
    },
    /**
     * 确定提交建材成功的图片
     */
    uploadCropImg() {
      this.dialogVisible = false;
      // 图片二进制文件
      let formData = new FormData();
      formData.append("filename", this.fileObj.name);
      formData.append("filetype", this.fileObj.type.replace("image/", ""));
      formData.append(
        "file",
        this.$refs.cropper.getCroppedCanvas().toDataURL()
      );
      // croImgUrl 建材后的文件上传地址
      this.$emit("imageUrl", "");
      this.$axios
        .post(this.path + "rest/foru/apd/upload", formData, {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          var data = res.data;
          if (data.result == "true") {
            var resultData = data.resultData;
            this.$emit("imageUrl", resultData.group + "/" + resultData.pathkey);
          } else {
            this.$error("图片读取失败，请重新选择");
          }
        })
        .catch(error => {
          this.$error("图片读取失败，请重新选择");
        });
    },
    /**
     * 取消剪裁图片
     */
    cancelCrop() {
      this.dialogVisible = false;
      this.cropImg = this.defaultCroImg;
    },
    handleError() {
      this.$notify.error({
        title: "上传失败",
        message: "图片上传接口上传失败，可更改为自己的服务器接口"
      });
    }
  },
  mounted() {
    if (!this.defaultCroImg) {
      this.cropImg = "./static/img/head.png";
    } else {
      this.cropImg = this.defaultCroImg;
    }
  },
  watch: {
    defaultCroImg(val) {
      this.cropImg = val;
    }
  }
};
</script>
